package swind.web.service.imp;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import swind.common.md5.MD5Utils;
import swind.web.dao.IRoleDao;
import swind.web.dao.IUserDao;
import swind.web.entities.ExamRole;
import swind.web.entities.ExamUser;
import swind.web.service.ILoginService;
import swind.web.vo.LoginUserVo;

@Transactional
@Service
public class LoginServiceImp implements ILoginService {
	
	
	@Resource(name="userDaoImp")
	IUserDao userDaoImp;
	
	@Resource(name="roleDaoImp")
	IRoleDao roleDaoImp;
	
	
	/**
	 * 根据userName得到用户对象
	 */
	@Override
	public ExamUser getUserByName(ExamUser eu){
		List<ExamUser> list=userDaoImp.find("from ExamUser eu where eu.userName='"+eu.getUserName()+"'");
		if(list.isEmpty()){
			return null;
		}
		return (ExamUser)list.get(0);
	}
	
	/**
	 * 根据ExamUser id得到role对象
	 * @param eu
	 * @return
	 */
	public List<ExamRole> getRoleByExamUser(ExamUser eu){
		Set<ExamRole> ers=eu.getExamRoles();
		List<ExamRole> list=new ArrayList<ExamRole>(ers);
		return list;
	}
	
	/**
	 * 是否已经过了锁定时间
	 */
	@Override
	public boolean isCrossLockTime(ExamUser eu){
		
		Calendar cl=Calendar.getInstance();
		cl.setTime(new Date());
		cl.add(Calendar.MINUTE,-5);
		//System.out.println(cl.getTime()+"--"+eu.getLastLockTime());
		if(cl.getTime().after(eu.getLastLockTime())){
			return true;
		}
		return false;
	}
	
	/**
	 * MD5处理密码是否正确
	 */
	@Override
	public boolean isPasswordTrue(LoginUserVo loginVo,ExamUser eu){
		String md5pass=MD5Utils.GetMD5Code(loginVo.getPassword());
		//System.out.println(md5pass);
		if(md5pass.equals(eu.getPassword())){
			return true;
		}
		return false;
	}
	
	@Override
	public boolean isPasswordTrue(LoginUserVo loginVo) {
		List<ExamUser> list=userDaoImp.find("from ExamUser eu where eu.userName='"+loginVo.getUserName()+"'");
		if(list.isEmpty()){
			return false;
		}else if(!list.isEmpty()){
			ExamUser eu=list.get(0);
			if(eu.getPassword().equals(loginVo.getPassword())){
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 增加错误登录次数
	 */
	@Override
	public void addLoginFailCount(ExamUser eu){
		eu.setLoginFailCount((byte)(eu.getLoginFailCount()+1));
		userDaoImp.update(eu);
	}
	
	/**
	 * 清空错误登录次数
	 */
	@Override
	public void clearLoginFailCount(ExamUser eu){
		eu.setLoginFailCount((byte)0);
		userDaoImp.update(eu);
	}
	
	/**
	 * 更新锁定时间
	 */
	@Override
	public void lockNow(ExamUser eu){
		eu.setLastLockTime(new Date());
		userDaoImp.update(eu);
	}

	
	
	
	
}
